import React, { useEffect, useCallback } from 'react';
import { useLocation } from 'react-router-dom';
import userService from '@/api/services/userService';
import { useRouter } from '@/router/hooks';
import Cookies from 'js-cookie';
import { setItem } from '@/utils/storage';
import { StorageEnum } from '@/types/enum';
import { USER_LIST } from '@/_mock/assets';
const { VITE_TOKEN: VITETOKEN } = import.meta.env;

const AuthPage = () => {
  const location = useLocation();
  const { replace } = useRouter();

  const auth = useCallback(async (uid:string, d:string, classid:string, courseid:string, type:string, appid: string) => {
    const res = await userService.authCx({ uid, d, classid, courseid, type, appid });
    return res;
  }, []);

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const uid = queryParams.get('uid');
    const type = queryParams.get('type');
    const classid = queryParams.get('classid');
    const courseid = queryParams.get('courseid');
    const d = queryParams.get('d');
    const backurl = queryParams.get('backurl');

    const authenticate = async () => {

      
      
      if (uid && d && backurl && classid && courseid && type) {
        try {
          
          
          // // hash 模式
          // const url = window.location.href
          // const regex = /&backurl=([^&]+)/;
          // const match = url.match(regex);
          // let backurlShare = ""
          // let appid = ""
          // if (match) {
          //   backurlShare = match[1];
          //   const regexAppid = /share\/([^\/]+)/;
          //   const matchAppId = backurlShare.match(regexAppid);
          //   if (matchAppId) {
          //     appid = match[1];
          //   } else {
          //     replace('/login');
          //   }
          // } else {
          //   replace('/login');
          // }

          // browser 模式
          let appid = ''
          const regexAppid = /share\/([^\/]+)/;
          const matchAppId = backurl.match(regexAppid);
          if (matchAppId) {
            appid = matchAppId[1];
          } else {
            replace('/login');
          }



          const data = await auth(uid, d, classid, courseid, type, appid);
          console.log(data?.role);
          
          if (data?.role == 'teacher') {
            const fakerUser = USER_LIST[0];
            let token = Cookies.get(VITETOKEN)
            const mergeUser = { ...fakerUser, "username": data?.username, avatar: fakerUser.avatar };
            setItem(StorageEnum.User, mergeUser);
            setItem(StorageEnum.Token, { accessToken:token, refreshToken:token });
            window.open(window.location.origin, '_self');
          } else {
            setItem(StorageEnum.User, {"username": data?.username});

            // // hash 模式
            // window.open(backurlShare, '_self');

            // browser 模式
            window.open(backurl, '_self');
          }
        } catch (error) {
          console.error('Authentication failed:', error);
          replace('/login');
        }
      } else {
        console.log('Missing required parameters');
        replace('/login');
      }
    };

    authenticate();
  }, [location.search, auth, replace]);

  return <></>;
};

export default AuthPage;